# !/usr/bin/env python
# encoding: utf-8


"""
  @author: gaogao
  @file: CommonDialog.py
  @time: 2022/4/17 13:19
  @desc:
"""
import configparser
import sys
from PyQt5 import QtWidgets
from PyQt5.QtCore import QSize, Qt, QRect, pyqtSignal
from PyQt5.QtGui import QIcon, QBrush, QColor, QPen, QFont, QPainter
from PyQt5.QtWidgets import QWidget, QDialog, QVBoxLayout, QGridLayout, QComboBox, QPushButton, QLabel, QMessageBox, \
    QHBoxLayout, QFormLayout, QLineEdit, QApplication, QFrame, QButtonGroup, QRadioButton, QGroupBox, QScrollArea, \
    QCheckBox
from gui.custom_widget.QSwitchButton import QSwitchButton
from gui import constant
from collections import namedtuple
from ATS.util.calcu_step_util import get_points_array, get_step_list
from ATS.application.LASER_App.L8164B_App import L8164B_App
import ast
import json
from gui.custom_widget.infoDialog import auto_close_dialog

current_unit_dict = {"uA": 0.000001, "mA": 0.001, "A": 1}
voltage_unit_dict = {"mV": 0.001, "V": 1}


class CommonDialog(QDialog):
    send_setting_info = pyqtSignal(object, object)

    def __init__(self, row_num, subdie, test_mode, dcp_list, current_name):
        super().__init__()
        with open("./static/style_sheet/origin.qss", mode='r', encoding='utf-8') as f:
            style_sheet = f.read()
        self.setStyleSheet(style_sheet)
        self.storage_list = [row_num, subdie, test_mode, dcp_list, current_name]
        self.current_name = current_name
        self.dcp_list = dcp_list
        self.row_num = row_num
        self.test_mode = test_mode
        self.subdie = subdie
        self.setWindowTitle(f"{subdie}-{test_mode}测试条件设置")
        # self.setWindowIcon(QIcon("./static/style_sheet/icons/logo.png"))
        self.initView()

    def initView(self):
        # IP 测试对应界面
        self.setFixedSize(QSize(950, 900))
        self.vl_dcp = QVBoxLayout(self)
        self.vl_dcp.setContentsMargins(0, 0, 0, 0)
        self.wd_ip = QWidget()
        self.hl_ip = QHBoxLayout(self.wd_ip)
        self.hl_ip.setSpacing(30)
        self.sa_dcp = QScrollArea(self)
        self.sa_dcp.setFixedHeight(self.height() - 80)
        self.sa_dcp.setFixedWidth(self.width() / 2 - 10)
        self.sa_dcp.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.sa_dcp.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.wd_left = QWidget()
        self.vl_left = QVBoxLayout(self.wd_left)
        self.genrate_widget(self.dcp_list, self.vl_left)

        self.sa_dcp.setWidget(self.wd_left)
        self.wd_right = QWidget()
        self.wd_right.setFixedWidth(self.width() / 2 - 10)
        self.wd_right.setFixedHeight(self.height() - 80)
        self.fl_right = QFormLayout(self.wd_right)
        self.fl_right.setHorizontalSpacing(25)
        self.fl_right.setVerticalSpacing(10)

        self.lb_l8164b = self.create_label_title("L8164B Settings")

        self.btn_group = QButtonGroup()
        self.hbtnlayout = QHBoxLayout()
        self.rb_fixed_wavelength = QRadioButton()
        self.rb_fixed_wavelength.setText("固定波长")
        self.rb_fixed_wavelength.setChecked(True)
        self.rb_fixed_wavelength.clicked.connect(self.show_8164_setting)
        self.rb_sweep_wavelength = QRadioButton()
        self.rb_sweep_wavelength.setText("扫描波长")
        self.rb_sweep_wavelength.clicked.connect(self.show_8164_setting)
        self.btn_group.addButton(self.rb_fixed_wavelength, 1)
        self.btn_group.addButton(self.rb_sweep_wavelength, 2)
        self.hbtnlayout.addWidget(self.rb_fixed_wavelength)
        self.hbtnlayout.addWidget(self.rb_sweep_wavelength)

        self.hl_contrains = QHBoxLayout()

        self.gb_singal_wavelenth = QGroupBox()
        self.gb_singal_wavelenth.setStyleSheet('QGroupBox{border:none;margin-top:0ex;}')

        self.gl_singal_settings = QGridLayout(self.gb_singal_wavelenth)
        self.gl_singal_settings.setContentsMargins(0, 0, 0, 0)

        self.wd_wave_len = QWidget()
        self.hl_wave_len = QHBoxLayout(self.wd_wave_len)
        self.hl_wave_len.setContentsMargins(0, 0, 0, 0)
        self.lb_wave_len = QLabel("Wave Length：")
        self.le_wave_len = QLineEdit()
        self.le_wave_len.setText("1330")
        self.le_wave_len.setClearButtonEnabled(True)
        self.le_wave_len.setFixedWidth(100)
        self.cb_wave_len = QComboBox()
        self.cb_wave_len.setFixedWidth(60)
        self.cb_wave_len.addItem("nm")
        self.hl_wave_len.addWidget(self.lb_wave_len, alignment=Qt.AlignLeft)
        self.hl_wave_len.addWidget(self.le_wave_len, alignment=Qt.AlignLeft)
        self.hl_wave_len.addWidget(self.cb_wave_len)
        self.hl_wave_len.addStretch(1)
        self.gl_singal_settings.addWidget(self.wd_wave_len, 0, 1)
        self.hl_contrains.addWidget(self.gb_singal_wavelenth)

        self.gb_sweep_wavelenth = QGroupBox()
        self.gb_sweep_wavelenth.hide()
        self.gb_sweep_wavelenth.setStyleSheet('QGroupBox{border:none;margin-top:0ex;}')

        self.gl_sweep_settings = QGridLayout(self.gb_sweep_wavelenth)
        self.gl_sweep_settings.setContentsMargins(0, 0, 0, 0)

        self.wd_lc_8164_step = QWidget()
        self.hl_lc_8164_step = QHBoxLayout(self.wd_lc_8164_step)
        self.hl_lc_8164_step.setContentsMargins(0, 0, 0, 0)
        self.lb_lc_8164_step = QLabel("步进设置：")
        self.le_lc_8164_step = QLineEdit()
        self.le_lc_8164_step.setText("1")
        self.le_lc_8164_step.setClearButtonEnabled(True)
        self.cb_lc_8164_step = QComboBox()
        self.cb_lc_8164_step.addItems(['nm'])
        self.hl_lc_8164_step.addWidget(self.lb_lc_8164_step)
        self.hl_lc_8164_step.addWidget(self.le_lc_8164_step)
        self.hl_lc_8164_step.addWidget(self.cb_lc_8164_step)
        self.hl_lc_8164_step.addStretch(1)
        self.wd_lc_8164_wave = QWidget()
        self.hl_lc_8164_wave = QHBoxLayout(self.wd_lc_8164_wave)
        self.hl_lc_8164_wave.setContentsMargins(0, 0, 0, 0)
        self.lb_lc_8164_wave = QLabel("波长设置：")
        self.le_lc_8164_wave_start = QLineEdit()
        self.le_lc_8164_wave_start.setText("1260")
        self.le_lc_8164_wave_start.setMinimumWidth(120)
        self.le_lc_8164_wave_start.setClearButtonEnabled(True)
        self.le_lc_8164_wave_stop = QLineEdit()
        self.le_lc_8164_wave_stop.setText("1360")
        self.le_lc_8164_wave_stop.setMinimumWidth(120)
        self.le_lc_8164_wave_stop.setClearButtonEnabled(True)
        self.cb_lc_8164_wave = QComboBox()
        self.cb_lc_8164_wave.addItems(['nm'])
        self.hl_lc_8164_wave.addWidget(self.lb_lc_8164_wave)
        self.hl_lc_8164_wave.addWidget(self.le_lc_8164_wave_start)
        self.hl_lc_8164_wave.addWidget(QLabel("~"))
        self.hl_lc_8164_wave.addWidget(self.le_lc_8164_wave_stop)
        self.hl_lc_8164_wave.addWidget(self.cb_lc_8164_wave)
        self.hl_lc_8164_wave.addStretch(1)
        self.gl_sweep_settings.addWidget(self.wd_lc_8164_step, 1, 1)
        self.gl_sweep_settings.addWidget(self.wd_lc_8164_wave, 0, 1)
        self.hl_contrains.addWidget(self.gb_sweep_wavelenth)
        self.wd_power = QWidget()
        self.hl_power = QHBoxLayout(self.wd_power)
        self.lb_power = QLabel("Power value:")
        self.le_power = QLineEdit()
        self.le_power.setText("10")
        self.le_power.setClearButtonEnabled(True)
        self.le_power.setFixedWidth(100)
        self.cb_power_unit = QComboBox()
        self.cb_power_unit.setFixedWidth(80)
        self.cb_power_unit.addItems(constant.POWER_UNIT)
        self.cb_power_unit.setCurrentIndex(0)
        self.hl_power.addWidget(self.lb_power, alignment=Qt.AlignLeft)
        self.hl_power.addWidget(self.le_power)
        self.hl_power.addWidget(self.cb_power_unit)
        self.hl_power.addStretch(1)
        self.lb_stable_schedule = QLabel("Stable Schedule：")
        self.le_stable_schedule = QLineEdit()
        self.le_stable_schedule.setText("3")
        self.le_stable_schedule.setClearButtonEnabled(True)
        self.le_stable_schedule.setFixedWidth(100)
        self.lb_n_7744 = self.create_label_title("n7744 Settings")
        self.wd_n7744_set = QWidget()
        self.hl_n7744_set = QHBoxLayout(self.wd_n7744_set)
        self.hl_n7744_set.setContentsMargins(0, 0, 0, 0)
        self.lb_n7744_atim = QLabel("积分时间:")
        self.le_n7744_atim = QLineEdit()
        self.le_n7744_atim.setText("100")
        self.le_n7744_atim.setMinimumWidth(80)
        self.le_n7744_atim.setClearButtonEnabled(True)
        self.cb_n7744_atim = QComboBox()
        self.cb_n7744_atim.addItems(['ns', "us", "ms", "s"])
        self.cb_n7744_atim.setCurrentIndex(1)
        self.hl_n7744_set.addWidget(self.lb_n7744_atim)
        self.hl_n7744_set.addWidget(self.le_n7744_atim)
        self.hl_n7744_set.addWidget(self.cb_n7744_atim)
        self.hl_n7744_set.addStretch(1)
        self.wd_n7744_range = QWidget()
        self.hl_n7744_range = QHBoxLayout(self.wd_n7744_range)
        self.hl_n7744_range.setContentsMargins(0, 0, 0, 0)
        self.lb_n7744_range = QLabel("量程设置：")
        self.le_n7744_range = QLineEdit()
        self.le_n7744_range.setMinimumWidth(120)
        self.le_n7744_range.setClearButtonEnabled(True)
        self.cb_n7744_range = QComboBox()
        self.cb_n7744_range.addItems(constant.N7744_RAGNE)
        self.hl_n7744_range.addWidget(self.lb_n7744_range)
        self.hl_n7744_range.addWidget(self.cb_n7744_range)
        self.hl_n7744_range.addStretch(1)

        # vppd
        self.lb_vppd = self.create_label_title("Vppd Settings")
        self.wd_vppd_set = QWidget()
        self.hl_vppd_set = QHBoxLayout(self.wd_vppd_set)
        self.hl_vppd_set.setContentsMargins(0, 0, 0, 0)
        self.lb_vppd_value = QLabel("Vppd:")
        self.le_vppd_value = QLineEdit()
        self.le_vppd_value.setText("2.5")
        self.le_vppd_value.setMinimumWidth(80)
        self.le_vppd_value.setClearButtonEnabled(True)
        self.lb_vppd_value_unit = QLabel("V")

        self.hl_vppd_set.addWidget(self.lb_vppd_value)
        self.hl_vppd_set.addWidget(self.le_vppd_value)
        self.hl_vppd_set.addWidget(self.lb_vppd_value_unit)
        self.hl_vppd_set.addStretch(1)

        # Loss_Coupler

        self.lb_loss_coupler = self.create_label_title("Loss_Coupler Settings")
        self.wd_loss_coupler = QWidget()
        self.hl_loss_coupler = QHBoxLayout(self.wd_loss_coupler)
        self.hl_loss_coupler.setContentsMargins(0, 0, 0, 0)
        self.lb_loss_coupler_value = QLabel("Loss_Coupler:")
        self.le_loss_coupler_value = QLineEdit()
        self.le_loss_coupler_value.setText("2.5")
        self.le_loss_coupler_value.setMinimumWidth(80)
        self.le_loss_coupler_value.setClearButtonEnabled(True)

        self.hl_loss_coupler.addWidget(self.lb_loss_coupler_value)
        self.hl_loss_coupler.addWidget(self.le_loss_coupler_value)
        self.hl_loss_coupler.addStretch(1)

        # PD Current@V
        self.lb_pd_current = self.create_label_title("PD Current@V Settings")
        self.wd_pd_current = QWidget()
        self.hl_pd_current = QHBoxLayout(self.wd_pd_current)
        self.hl_pd_current.setContentsMargins(0, 0, 0, 0)
        self.lb_pd_current_value = QLabel("Current@V:")
        self.le_pd_current_value = QLineEdit()
        self.le_pd_current_value.setText("2.5")
        self.le_pd_current_value.setMinimumWidth(80)
        self.le_pd_current_value.setClearButtonEnabled(True)
        self.lb_pd_current_unit = QLabel("V")
        self.hl_pd_current.addWidget(self.lb_pd_current_value)
        self.hl_pd_current.addWidget(self.le_pd_current_value)
        self.hl_pd_current.addWidget(self.lb_pd_current_unit)
        self.hl_pd_current.addStretch(1)

        # LCA测试等待时间
        self.lb_lca_time = self.create_label_title("LCA test wait time")
        self.wd_lca_time = self.create_widget("Wait_time", "7", "s")

        # 探针的状态设置
        self.lb_probe_state = self.create_label_title("Probe State")
        self.wd_check_box = self.create_checkbox()
        tips = QLabel("勾选为探针执行升降操作;取消为探针分离,不执行下降操作.")
        tips.setStyleSheet("color:red;")

        # oo objectname
        # 8164
        self.rb_fixed_wavelength.setObjectName("rb_fixed_wavelength")
        self.rb_sweep_wavelength.setObjectName("rb_sweep_wavelength")
        self.le_wave_len.setObjectName("le_wave_len")
        self.le_power.setObjectName("le_power")
        self.cb_power_unit.setObjectName("cb_power_unit")
        self.le_stable_schedule.setObjectName("le_stable_schedule")
        self.le_lc_8164_wave_start.setObjectName("le_lc_8164_wave_start")
        self.le_lc_8164_wave_stop.setObjectName("le_lc_8164_wave_stop")
        self.le_lc_8164_step.setObjectName("le_lc_8164_step")
        # n7744
        self.le_n7744_atim.setObjectName("le_n7744_atim")
        self.cb_n7744_atim.setObjectName("cb_n7744_atim")
        self.cb_n7744_range.setObjectName("cb_n7744_range")
        # vppd
        self.le_vppd_value.setObjectName("le_vppd_value")
        # Loss_Coupler
        self.le_loss_coupler_value.setObjectName("le_loss_coupler_value")
        # PD Current@V
        self.le_pd_current_value.setObjectName("le_pd_current_value")

        # LCA
        # self.le_lca_time_value.setObjectName("le_lca_time_value")

        self.pb_submit = QPushButton("保存设置")
        self.pb_submit.clicked.connect(self.save_and_send_setting)
        self.pb_submit.setFixedWidth(100)
        # self.fl_left.addRow(self.lb_output_state, self.pb_switch)
        self.fl_right.addRow(self.lb_l8164b)
        self.fl_right.addRow(self.hbtnlayout)
        self.fl_right.addRow(self.hl_contrains)
        # self.fl_right.addRow(self.gl_singal_settings)
        self.fl_right.addRow(self.wd_power)
        # self.fl_right.addRow(self.lb_power_unit, self.cb_power_unit)
        self.fl_right.addRow(self.lb_stable_schedule, self.le_stable_schedule)
        self.fl_right.addRow(self.lb_n_7744)
        self.fl_right.addRow(self.wd_n7744_set)
        self.fl_right.addRow(self.wd_n7744_range)
        self.fl_right.addRow(self.lb_vppd)
        self.fl_right.addRow(self.wd_vppd_set)
        self.fl_right.addRow(self.lb_loss_coupler)
        self.fl_right.addRow(self.wd_loss_coupler)
        self.fl_right.addRow(self.lb_pd_current)
        self.fl_right.addRow(self.wd_pd_current)
        self.fl_right.addRow(self.lb_lca_time)
        self.fl_right.addRow(self.wd_lca_time)
        self.fl_right.addRow(self.lb_probe_state)
        self.fl_right.addRow(self.wd_check_box)
        self.fl_right.addRow(tips)

        self.hl_ip.addWidget(self.sa_dcp)
        self.hl_ip.addStretch(1)
        self.hl_ip.addWidget(self.wd_right)
        self.hl_ip.addStretch(1)
        self.vl_dcp.addWidget(self.wd_ip)
        self.vl_dcp.addWidget(self.pb_submit, alignment=Qt.AlignHCenter)
        self.vl_dcp.addStretch(1)

    def create_label_title(self, l_title):
        lb_title = QLabel(l_title)
        lb_title.setStyleSheet(
            "color:white;background:gray;border-width:0;border-style:outset;font-size:20px;color:white;padding:5px")
        return lb_title

    def create_widget(self, l_title, le_value, l_unit=None):
        wd_common = QWidget()
        hl_common = QHBoxLayout(wd_common)
        hl_common.setContentsMargins(0, 0, 0, 0)
        lb_title_value = QLabel(f"{l_title}:")
        le_content_value = QLineEdit()
        le_content_value.setText(le_value)
        le_content_value.setObjectName(f"le_{l_title}")
        le_content_value.setMinimumWidth(80)
        le_content_value.setClearButtonEnabled(True)
        hl_common.addWidget(lb_title_value)
        hl_common.addWidget(le_content_value)
        if l_unit:
            lb_unit = QLabel(l_unit)
            hl_common.addWidget(lb_unit)
        hl_common.addStretch(1)
        return wd_common

    def create_checkbox(self):
        wd_common = QWidget()
        hl_common = QHBoxLayout(wd_common)
        hl_common.setContentsMargins(0, 0, 0, 0)
        for idx in range(4):
            if idx == 0:
                cb1 = QCheckBox("P1")
                cb1.setObjectName("cb_p1")
                cb1.setChecked(True)
                hl_common.addWidget(cb1)
            elif idx == 1:
                cb2 = QCheckBox("P2")
                cb2.setObjectName("cb_p2")
                cb2.setChecked(True)
                hl_common.addWidget(cb2)
            elif idx == 2:
                cb3 = QCheckBox("H1")
                cb3.setObjectName("cb_h1")
                cb3.setChecked(True)
                hl_common.addWidget(cb3)
            else:
                cb4 = QCheckBox("H2")
                cb4.setObjectName("cb_h2")
                cb4.setChecked(True)
                hl_common.addWidget(cb4)

        hl_common.addStretch(1)
        return wd_common

    def genrate_widget(self, dcp_list, contrainer):
        smu_list = list(dcp_list.keys())
        for dcp in range(len(smu_list)):
            cb_state = QCheckBox()
            cb_state.setText("禁用")
            cb_state.setChecked(False)
            cb_state.toggled.connect(self.set_item_state)
            contrainer.addWidget(cb_state)
            wd_contrainer = QWidget()
            wd_contrainer.setEnabled(False)
            fl_contrainer = QFormLayout(wd_contrainer)
            fl_contrainer.setVerticalSpacing(10)
            lb_dcpsmu = QLabel(f"{smu_list[dcp]} Settings")
            lb_dcpsmu.setFixedHeight(30)
            lb_dcpsmu.setStyleSheet(
                "color:white;background:gray;border-width:0;border-style:outset;font-size:20px;color:white;padding:5px")
            bg_group = QButtonGroup(fl_contrainer)
            hl_voltage = QHBoxLayout()
            rb_fixed_voltage = QRadioButton()
            rb_fixed_voltage.setText("固定电压")
            rb_sweep_voltage = QRadioButton()
            rb_sweep_voltage.setText("扫描电压")
            rb_sweep_voltage.setChecked(True)
            hl_voltage.addWidget(rb_fixed_voltage)
            hl_voltage.addWidget(rb_sweep_voltage)
            bg_group.addButton(rb_fixed_voltage, 1)
            bg_group.addButton(rb_sweep_voltage, 2)
            rb_fixed_voltage.toggled.connect(lambda: self.show_voltage_setting(1))
            rb_sweep_voltage.toggled.connect(lambda: self.show_voltage_setting(2))
            hl_voltage_container = QHBoxLayout()
            gb_singal_voltage = QGroupBox()
            gb_singal_voltage.hide()
            gb_singal_voltage.setStyleSheet('QGroupBox{border:none;margin-top:0ex;}')
            gl_singal_voltage = QGridLayout(gb_singal_voltage)
            gl_singal_voltage.setSpacing(0)
            lb_voltage_value = QLabel("Voltage Value：")
            wd_voltage_value = QWidget()
            hl_voltage_value = QHBoxLayout(wd_voltage_value)
            hl_voltage_value.setContentsMargins(0, 0, 0, 0)
            le_voltage_value = QLineEdit()
            le_voltage_value.setText("2")
            le_voltage_value.setClearButtonEnabled(True)
            le_voltage_value.setFixedWidth(100)
            cb_voltage_value = QComboBox()
            cb_voltage_value.setFixedWidth(60)
            cb_voltage_value.addItems(constant.VOLTAGE_UNIT)
            cb_voltage_value.setCurrentIndex(1)
            hl_voltage_value.addWidget(le_voltage_value, alignment=Qt.AlignLeft)
            hl_voltage_value.addWidget(cb_voltage_value)
            gl_singal_voltage.addWidget(lb_voltage_value, 0, 1)
            gl_singal_voltage.addWidget(wd_voltage_value, 0, 2)
            gb_sweep_voltage = QGroupBox()
            gb_sweep_voltage.setStyleSheet('QGroupBox{border:none;margin-top:0ex;}')
            gl_sweep_voltage = QGridLayout(gb_sweep_voltage)
            lb_start_voltage_value = QLabel("Voltage Start：")
            wd_start_voltage_value = QWidget()
            hl_start_voltage_value = QHBoxLayout(wd_start_voltage_value)
            hl_start_voltage_value.setContentsMargins(0, 0, 0, 0)
            le_start_voltage_value = QLineEdit()
            le_start_voltage_value.setText("0")
            le_start_voltage_value.setClearButtonEnabled(True)
            le_start_voltage_value.setFixedWidth(100)
            cb_start_voltage_value = QComboBox()
            cb_start_voltage_value.setFixedWidth(60)
            cb_start_voltage_value.addItems(constant.VOLTAGE_UNIT)
            cb_start_voltage_value.setCurrentIndex(1)
            hl_start_voltage_value.addWidget(le_start_voltage_value, alignment=Qt.AlignLeft)
            hl_start_voltage_value.addWidget(cb_start_voltage_value)
            gl_sweep_voltage.addWidget(lb_start_voltage_value, 0, 1)
            gl_sweep_voltage.addWidget(wd_start_voltage_value, 0, 2)
            lb_stop_voltage_value = QLabel("Voltage Stop：")
            wd_stop_voltage_value = QWidget()
            hl_stop_voltage_value = QHBoxLayout(wd_stop_voltage_value)
            hl_stop_voltage_value.setContentsMargins(0, 0, 0, 0)
            le_stop_voltage_value = QLineEdit()
            le_stop_voltage_value.setText("2")
            le_stop_voltage_value.setClearButtonEnabled(True)
            le_stop_voltage_value.setFixedWidth(100)
            cb_stop_voltage_value = QComboBox()
            cb_stop_voltage_value.setFixedWidth(60)
            cb_stop_voltage_value.addItems(constant.VOLTAGE_UNIT)
            cb_stop_voltage_value.setCurrentIndex(1)
            hl_stop_voltage_value.addWidget(le_stop_voltage_value, alignment=Qt.AlignLeft)
            hl_stop_voltage_value.addWidget(cb_stop_voltage_value)

            gl_sweep_voltage.addWidget(lb_stop_voltage_value, 1, 1)
            gl_sweep_voltage.addWidget(wd_stop_voltage_value, 1, 2)

            lb_voltage_points = QLabel("Voltage Points：")

            le_voltage_points = QLineEdit()
            le_voltage_points.setText("101")
            le_voltage_points.setClearButtonEnabled(True)
            le_voltage_points.setFixedWidth(100)

            gl_sweep_voltage.addWidget(lb_voltage_points, 2, 1)
            gl_sweep_voltage.addWidget(le_voltage_points, 2, 2)

            hl_voltage_container.addWidget(gb_singal_voltage)
            hl_voltage_container.addWidget(gb_sweep_voltage)

            lb_voltage_range = QLabel("Voltage Range：")
            cb_voltage_range = QComboBox()
            cb_voltage_range.setFixedWidth(100)
            cb_voltage_range.addItems(constant.U2722_VOLTAGE_RANGE)
            cb_voltage_range.setCurrentIndex(1)

            lb_current_nplc = QLabel("Current Nplc：")
            le_current_nplc = QLineEdit()
            le_current_nplc.setText("4")
            le_current_nplc.setClearButtonEnabled(True)
            le_current_nplc.setFixedWidth(100)

            lb_current_range = QLabel("Current Range：")
            cb_current_range = QComboBox()
            cb_current_range.setFixedWidth(100)
            cb_current_range.addItems(constant.U2722_CURRENT_RANGE)
            cb_current_range.setCurrentIndex(5)

            lb_current_limit = QLabel("Current Limit：")
            lb_current_limit.hide()
            wd_current_limit = QWidget()
            wd_current_limit.hide()
            hl_current_limit = QHBoxLayout(wd_current_limit)
            hl_current_limit.setContentsMargins(0, 0, 0, 0)
            le_current_limit = QLineEdit()
            le_current_limit.setText("120")
            le_current_limit.setClearButtonEnabled(True)
            le_current_limit.setFixedWidth(100)
            cb_current_limit = QComboBox()
            cb_current_limit.setFixedWidth(60)
            cb_current_limit.addItems(constant.CURRENT_LIMIT)
            cb_current_limit.setCurrentIndex(1)
            hl_current_limit.addWidget(le_current_limit, alignment=Qt.AlignLeft)
            hl_current_limit.addWidget(cb_current_limit)

            ck_measure = QCheckBox("measure")
            ck_measure.setChecked(False)

            # lb_vh = QLabel("vh value")
            # cb_vh = QComboBox()
            # cb_vh.addItems(["none", "vh1", "vh3"])
            # cb_vh.setFixedWidth(60)
            # cb_vh.currentIndexChanged.connect(self.voltage_set_invalid)
            f_divide = QFrame()
            f_divide.setMinimumWidth(self.width() / 2 - 10)
            f_divide.setFrameShape(QFrame.HLine)
            f_divide.setStyleSheet("QFrame{background:blue;min-width:5px}")
            fl_contrainer.addRow(lb_dcpsmu)
            fl_contrainer.addRow(hl_voltage)
            fl_contrainer.addRow(hl_voltage_container)
            fl_contrainer.addRow(lb_voltage_range, cb_voltage_range)
            fl_contrainer.addRow(lb_current_nplc, le_current_nplc)
            fl_contrainer.addRow(lb_current_range, cb_current_range)
            fl_contrainer.addRow(lb_current_limit, wd_current_limit)
            fl_contrainer.addRow(lb_current_limit, wd_current_limit)
            # fl_contrainer.addRow(lb_vh, cb_vh)
            fl_contrainer.addRow(ck_measure)
            # contrainer.addRow(wd_contrainer)
            contrainer.addWidget(wd_contrainer)
            contrainer.addStretch(1)
            # objectName Group
            # sweep
            cb_state.setObjectName(f"ck_state{dcp}")
            rb_sweep_voltage.setObjectName(f"rb_sweep_voltage{dcp}")
            rb_fixed_voltage.setObjectName(f"rb_fixed_voltage{dcp}")
            le_start_voltage_value.setObjectName(f"le_start_voltage_value{dcp}")
            le_stop_voltage_value.setObjectName(f"le_stop_voltage_value{dcp}")
            le_voltage_points.setObjectName(f"le_voltage_points{dcp}")
            cb_start_voltage_value.setObjectName(f"cb_start_voltage_value{dcp}")
            cb_stop_voltage_value.setObjectName(f"cb_stop_voltage_value{dcp}")
            # spot
            le_voltage_value.setObjectName(f"le_voltage_value{dcp}")
            cb_voltage_value.setObjectName(f"cb_voltage_value{dcp}")
            cb_voltage_range.setObjectName(f"cb_voltage_range{dcp}")
            cb_current_range.setObjectName(f"cb_current_range{dcp}")
            le_current_nplc.setObjectName(f"le_current_nplc{dcp}")
            cb_current_range.setObjectName(f"cb_current_range{dcp}")
            cb_current_limit.setObjectName(f"cb_current_limit{dcp}")
            le_current_limit.setObjectName(f"le_current_limit{dcp}")
            ck_measure.setObjectName(f"ck_measure{dcp}")
            # cb_vh.setObjectName(f"cb_vh{dcp}")
            self.update()

    def _save_hsp(self, config_obj, auto_save_list):
        self._common_save_hsp(self, config_obj, self.current_name, auto_save_list)
        if not config_obj.has_section("dialog_init"):
            config_obj.add_section(f"dialog_init")
        config_obj.set(f"dialog_init", f"{self.current_name}", json.dumps(self.storage_list))

    def _common_save_hsp(self, parent_widget, config_obj, section_head, auto_save_dict):
        # create section
        for tool_head_name in auto_save_dict:
            child_list = parent_widget.findChildren(auto_save_dict[tool_head_name])
            current_section = f"{section_head}/{tool_head_name}"
            config_obj.add_section(current_section)
            for tool_obj in child_list:
                id_name = tool_obj.objectName()
                if "qt_spinbox_lineedit" in id_name or "qt_calendar_yearedit" in id_name or "lbt_title" in id_name or id_name == "":
                    continue
                tool_obj = parent_widget.findChild(auto_save_dict[tool_head_name], id_name)
                if tool_obj:
                    if tool_head_name == "rb":
                        raw_value = tool_obj.isChecked()
                    elif tool_head_name == "le":
                        raw_value = tool_obj.text()
                    elif tool_head_name == "sb":
                        raw_value = tool_obj.value()
                    elif tool_head_name == "cb":
                        raw_value = tool_obj.currentIndex()
                    elif tool_head_name == "ck":
                        raw_value = tool_obj.isChecked()
                    elif tool_head_name == "sw":
                        raw_value = tool_obj.getState()
                    config_obj.set(current_section, id_name,
                                   raw_value if isinstance(raw_value, str) else json.dumps(raw_value))

    def _recall_hsp(self, config_obj):
        self._common_recall_hsp(self, config_obj)
        self.show_8164_setting()  # 变化

    def _common_recall_hsp(self, parent_widget, config_obj):
        auto_save_dict = {f"{self.current_name}/rb": QRadioButton, f"{self.current_name}/le": QLineEdit,
                          f"{self.current_name}/ck": QCheckBox, f"{self.current_name}/cb": QComboBox}
        for section_name in auto_save_dict:
            for option_name in config_obj.options(section_name):
                tool_obj = parent_widget.findChild(auto_save_dict[section_name], option_name)
                if tool_obj:
                    if section_name[-2:] == "rb":
                        tool_obj.setChecked(json.loads(config_obj.get(section_name, option_name)))
                    elif section_name[-2:] == "le":
                        tool_obj.setText(config_obj.get(section_name, option_name))
                    elif section_name[-2:] == "sb":
                        tool_obj.setValue(json.loads(config_obj.get(section_name, option_name)))
                    elif section_name[-2:] == "cb":
                        tool_obj.setCurrentIndex(json.loads(config_obj.get(section_name, option_name)))
                    elif section_name[-2:] == "ck":
                        tool_obj.setChecked(json.loads(config_obj.get(section_name, option_name)))
                    elif section_name[-2:] == "sw":
                        tool_obj.setState(json.loads(config_obj.get(section_name, option_name)))

    def save_and_send_setting(self):
        set_info = namedtuple("setting_info",
                              'row_num,subdie,test_item,vppd,loss_coupler,current_v,smu_setting,l8164_setting,n7744_setting,lca_wait_time,probe_state_dict')
        smu_setting = self.get_left_setting_info()
        l8164_setting = self.get_n8164_setting_info()
        n7744_setting = self.get_n7744_setting_info()
        vppd = self.get_vppd_value()
        loss_coupler = self.get_loss_coupler()
        current_v = self.get_pd_current_v()
        lca_wait_time = self.get_lca_wait_time()
        probe_state_dict = self.get_probe_check_state()
        if l8164_setting and n7744_setting and lca_wait_time and probe_state_dict:
            self.send_setting_info.emit(f"{self.row_num}_{self.subdie}_{self.test_mode}",
                                        set_info(self.row_num, self.subdie, self.test_mode, vppd, loss_coupler,
                                                 current_v,
                                                 smu_setting,
                                                 l8164_setting._asdict(),
                                                 n7744_setting._asdict(), lca_wait_time, probe_state_dict))
            self.close()

    def get_lca_wait_time(self):
        lca_wait_time = self.wd_lca_time.children()[2].text()
        return lca_wait_time if lca_wait_time else "7"

    def get_probe_check_state(self):
        probe_state_dict = {}
        for child in self.wd_check_box.children():
            if isinstance(child, QtWidgets.QHBoxLayout):
                continue
            probe_text = child.text()
            if probe_text == "H1":
                probe_key = "W"
            elif probe_text == "H2":
                probe_key = "E"
            else:
                probe_key = probe_text
            probe_state_dict[probe_key] = child.isChecked()
        print("probe_state",probe_state_dict)
        return probe_state_dict

    def get_n8164_setting_info(self):
        l8164_setting = namedtuple('l8164_setting', 'title,wave_length, power_value,power_unit,stable_time')
        l8164_tile = self.lb_l8164b.text()
        power_value = self.le_power.text()
        power_unit = self.cb_power_unit.currentText()
        stable_time = self.le_stable_schedule.text()
        check_id = self.btn_group.checkedId()
        wave_list = []
        if check_id == 1:
            wave_length = self.le_wave_len.text()
            wave_list.append(wave_length)
        else:
            start_wave = self.le_lc_8164_wave_start.text()
            stop_wave = self.le_lc_8164_wave_stop.text()
            step_wave = self.le_lc_8164_step.text()
            wave_list.append(start_wave)
            wave_list.append(stop_wave)
            wave_list.append(step_wave)
            if start_wave and stop_wave and step_wave:
                wave_list = get_step_list(float(start_wave), float(stop_wave), float(step_wave))
                # power_result = L8164B_App("SS3").query_sweep_pmax(start_wave, stop_wave)
                power_result = 10
                if float(power_value) > power_result:
                    auto_close_dialog(self, "8164的功率超过了波长范围内的最大功率")
                    return

        return l8164_setting("SS3", wave_list, power_value, power_unit, stable_time)

    def get_n7744_setting_info(self):
        n7744_setting = namedtuple('n7744_setting', 'title,atim, power_range')
        n7744_atim = self.le_n7744_atim.text()
        n7744_atim_unit = self.cb_n7744_atim.currentText()
        n7744_range = self.cb_n7744_range.currentText()
        return n7744_setting("SS2", n7744_atim + n7744_atim_unit, n7744_range)

    def get_vppd_value(self):
        vppd_value = self.le_vppd_value.text()
        return vppd_value if vppd_value else ""

    def get_loss_coupler(self):
        loss_coupler = self.le_loss_coupler_value.text()
        return loss_coupler if loss_coupler else ""

    def get_pd_current_v(self):
        pd_current_v = self.le_pd_current_value.text()
        return pd_current_v if pd_current_v else ""

    def get_left_setting_info(self):
        left_list = self.wd_left.children()[1:]
        test_paramater = namedtuple("smu_setting",
                                    "dcp,title,smu,channel,mode,voltage_list,voltage_range,nplc,current_range,current_limit,is_measure")
        result_list = []
        for left in range(0, len(left_list), 2):
            if left_list[left].isChecked():
                child_list = left_list[left + 1].children()[1:]
                title = child_list[0].text().strip().split(" ")[0]
                tcp = title.split(":")[0]
                title_alias = title.split(":")[1]
                content = self.dcp_list[title]
                # print("content", content)
                tuple_smu = tuple(content[1:-1].split(","))
                # print("tuple_smu", tuple_smu)
                smu = tuple_smu[0]
                channel = tuple_smu[1]
                voltage_list = []
                mode = ""
                if child_list[1].isChecked():
                    mode = "spot"
                    singal_voltage = child_list[3].children()[2].children()[1].text()
                    voltage_unit = child_list[3].children()[2].children()[2].currentText()
                    voltage_list.append(float(singal_voltage) * voltage_unit_dict[voltage_unit])
                if child_list[2].isChecked():
                    mode = "sweep"
                    start_voltage = child_list[4].children()[2].children()[1].text()
                    start_voltage_unit = child_list[4].children()[2].children()[2].currentText()
                    stop_voltage = child_list[4].children()[4].children()[1].text()
                    stop_voltage_unit = child_list[4].children()[4].children()[2].currentText()
                    points = child_list[4].children()[6].text()
                    if start_voltage and stop_voltage and points:
                        voltage_list = get_points_array(float(start_voltage) * voltage_unit_dict[start_voltage_unit],
                                                        float(stop_voltage) * voltage_unit_dict[stop_voltage_unit],
                                                        int(points))
                voltage_range = child_list[6].currentText()
                nplc = child_list[8].text()
                current_range = child_list[10].currentText()
                current_limit = child_list[12].children()[1].text()
                current_unit = child_list[12].children()[2].currentText()
                # vh = child_list[14].currentText()
                # print(vh)
                measure_state = child_list[13].isChecked()
                # print("measure_state", measure_state)
                result_list.append(
                    test_paramater(tcp, title_alias, smu, channel, mode, voltage_list, voltage_range, nplc,
                                   current_range,
                                   float(current_limit) * current_unit_dict[current_unit], measure_state)._asdict())
        return result_list

    def show_8164_setting(self):
        if self.rb_fixed_wavelength.isChecked():
            self.gb_singal_wavelenth.show()
            self.gb_sweep_wavelenth.hide()
        else:
            self.gb_singal_wavelenth.hide()
            self.gb_sweep_wavelenth.show()

    def voltage_set_invalid(self, cb_index):
        if cb_index == 0:
            self.sender().parent().children()[4].setChecked(True)
            self.sender().parent().children()[5].setChecked(True)
        else:
            self.sender().parent().children()[4].setCheckable(True)
            self.sender().parent().children()[4].setChecked(False)
            self.sender().parent().children()[5].setCheckable(True)
            self.sender().parent().children()[5].setChecked(False)

    def show_voltage_setting(self, rb_index):
        if rb_index == 1:
            self.sender().parent().children()[4].show()
            self.sender().parent().children()[5].hide()
        else:
            self.sender().parent().children()[4].hide()
            self.sender().parent().children()[5].show()

    def set_item_state(self, value):
        widget_list = self.sender().parent().children()
        current_index = widget_list.index(self.sender())
        if value:
            self.sender().setText("启用")
            widget_list[current_index + 1].setEnabled(True)
        else:
            self.sender().setText("禁用")
            widget_list[current_index + 1].setEnabled(False)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = CommonDialog(1, "D1", "iv_sweep", {'DCP02:SMU03': '(SMU02,3)',
                                                'DCP05:SMU06': '(SMU03,3)', }, "")
    window.show()
    sys.exit(app.exec())
